package com.example.openanprtest2;


import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;

public class JavavcCameraTest2 {
//    static{ nu.pattern.OpenCV.loadShared(); }
    public static void main(String[] args) throws Exception, InterruptedException{
        OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
//        调整 Thread.sleep() 的时间（如从 50 毫秒增加到 100 毫秒）。
//        降低摄像头分辨率：
//        grabber.setImageWidth(640);
//        grabber.setImageHeight(480);

        grabber.start();   //开始获取摄像头数据
        CanvasFrame canvas = new CanvasFrame("摄像头");//新建一个窗口
        canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas.setAlwaysOnTop(true);


        // 添加键盘监听器
        canvas.getCanvas().addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_S) { // 按下 S 键保存图片
                    try {
                        // 捕获当前帧
                        Frame frame = grabber.grab();
                        if (frame != null) {
                            // 将帧转换为 BufferedImage
                            Java2DFrameConverter converter = new Java2DFrameConverter();
                            BufferedImage image = converter.convert(frame);

                            // 保存为图片文件
                            ImageIO.write(image, "jpg", new File("capture_" + System.currentTimeMillis() + ".jpg"));
                            System.out.println("截图已保存！");

                            //          扩展2 Base64 编码：将当前帧转换为 Base64 编码。
//            Frame frame = grabber.grab();
//            Java2DFrameConverter converter = new Java2DFrameConverter();
//            BufferedImage image = converter.convert(frame);
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            ImageIO.write(image, "jpg", baos);
                            String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());
                            System.out.println("Base64: " + base64);


                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        // 实时显示摄像头画面
        while(true){
            if(!canvas.isDisplayable()){//窗口是否关闭
                grabber.stop();//停止抓取
                System.exit(2);//退出
                break;
            }
            canvas.showImage(grabber.grab());//获取摄像头图像并放到窗口上显示， 这里的Frame frame=grabber.grab(); frame是一帧视频图像
            Thread.sleep(200);//50毫秒刷新一次图像
        }


//              if (someCondition) {
        //扩展1 保存截图：按下某个键时保存当前帧为图片。
//        Frame frame = grabber.grab();
//        Java2DFrameConverter converter = new Java2DFrameConverter();
//        BufferedImage image = converter.convert(frame);
//        ImageIO.write(image, "jpg", new File("screenshot.jpg"));
//            }

//           扩展2 Base64 编码：将当前帧转换为 Base64 编码。
//            Frame frame = grabber.grab();
//            Java2DFrameConverter converter = new Java2DFrameConverter();
//            BufferedImage image = converter.convert(frame);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        ImageIO.write(image, "jpg", baos);
//        String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());
//        System.out.println("Base64: " + base64);

    }
}